package work02.w5.control.persistence;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;


public class Storage {
	File file;
	FileSaveLoadSystemByXML saver;
	static Storage me;
	
	public static Storage getInstance(){
		if(me==null)
			me=new Storage();
		return me;
	}
	private Storage() {
		File file=null;
		try {
			file = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
		} catch (URISyntaxException e) {
			try {
				file=new File(Storage.class.getClassLoader().getResource("/").toURI());
			} catch (URISyntaxException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
//		 file=file.getAbsoluteFile();
//		try{
//		while (true) {
//			if (file.getPath().endsWith("\\Calendar")) {
//				break;
//			}
////			file = file.getParentFile();
//		}
//		}catch (Exception e){};
		this.file = file;
		this.saver = new FileSaveLoadSystemByXML();
	}

	/**
	 * @param name
	 *            名称要唯一，建议包名+类名用下划线连接如:work_Date
	 * @param storaged
	 *            被存储的对象，为了保证存储的可靠性，建议为pojo对象
	 */
	public synchronized boolean save(String name, Object storaged) {
		String path = file.getPath() + "\\Config\\" + name;
		
		try {
			return saver.save(path, storaged);
		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	public synchronized Object load(String name) {
		String path = file.getPath() + "\\Config\\" + name;
		return saver.load(path);
	}
}
